package com.dingxin.portal.common.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.Dialect;
import org.springframework.jdbc.support.incrementer.AbstractSequenceMaxValueIncrementer;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;


public class SessionFactoryBean extends LocalSessionFactoryBean {
	private Map<String,AbstractSequenceMaxValueIncrementer> incrementers=new HashMap<String,AbstractSequenceMaxValueIncrementer>();
	private List<String> incrementerNames;

	public void setIncrementerNames(List<String> incrementerNames) {
		this.incrementerNames = incrementerNames;
	}

	protected void postProcessConfiguration(Configuration configuration)
        throws HibernateException {
        super.postProcessConfiguration(configuration);
        Dialect dialect = Dialect.getDialect(configuration.getProperties());
        if(!dialect.supportsSequences()){
        	return;
        }
		for (String incrementerName : incrementerNames) {
			final String NextValString=dialect.getSequenceNextValString(incrementerName);
			AbstractSequenceMaxValueIncrementer incrementer= new AbstractSequenceMaxValueIncrementer(){
				protected String getSequenceQuery() {
					return NextValString;
				}
			};
			incrementer.setIncrementerName(incrementerName);
			incrementer.setDataSource(getConfigTimeDataSource());
			incrementer.afterPropertiesSet();
			incrementers.put(incrementerName,incrementer);
		}
	}
	protected AbstractSequenceMaxValueIncrementer getIncrementer(String incrementerName){
		return incrementers.get(incrementerName);
	}
}
